<template>
  <div>
    <el-card class="search-card">
      <table-form
        ref="tableForm"
        :formItemList="formItemList"
        @getFormData="getFormDataFunc"
      />
    </el-card>
    <el-card class="table-card">
      <basic-table
        showActionCol
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :pagination="pagination"
        :pageSizes="pageSizes"
        :showSelectCol="false"
        :actionColWidth="200"
        :actionRender="actionRenderFunc"
        @pageChange="handlePageChange"
        @pageSizeChange="handlePageSizeChange"
      >
        <div slot="content_context">
          <el-button
            :loading="addBtnLoading"
            type="primary"
            size="mini"
            icon="el-icon-plus"
            @click="handleChooseAdd(null)"
          >新增单据</el-button
          >
        </div>
      </basic-table>
    </el-card>
  </div>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import TableForm from './components/TableForm';
import BasicTable from '@/components/BasicTable';
import { formItemList, tableColumns } from './constants/indexPage';
import { isResponseSuccess } from '@/utils/bizUtils';
import { getBtnsId } from '@/libs/btnsPermission';

export default {
  components: {
    TableForm,
    BasicTable
  },
  data () {
    return {
      formItemList: formItemList, // 表单列集合
      tableInfo: {
        list: [], // 表格数据
        columns: tableColumns, // 表格columns
        loading: false // 表格加载loading
      },
      pagination: {
        nowPage: 1, // 当前页码
        totalNum: 0, // 总条数
        pageShow: 10, // 每页条数
      },
      pageSizes: [10, 20, 30, 40], // 每页条数size集合
      addBtnLoading: false, // 新增按钮loading
      formData: {},
    }
  },
  mounted () {
    this.$refs.tableForm.handleQueryForm();
    let curBtnId = getBtnsId('查询');
    sessionStorage.setItem('buttonId', curBtnId);
    // 原材料待办单据号
    const { rawMaterialTodoRecordNo, isPriceCycle } = this.$route.query;
    if (rawMaterialTodoRecordNo) {
      this.handleChooseAdd(rawMaterialTodoRecordNo)
    }
    if (isPriceCycle) {
      this.handleChooseAdd()
    }
  },
  methods: {
    /* jsx渲染action方法 */
    actionRenderFunc (h, { index, row }) {
      return (
        <div class="table-action">
          {
            row.actions.map(item => {
              if (item.type == 'delete') {
                return (
                  <el-popconfirm title="确定删除吗？" onConfirm={() => { this.handleChooseBatchStatus({ item, row }) }}><el-button slot="reference" type="text" size="large">{item.label}</el-button></el-popconfirm>
                )
              } else {
                return (
                  <el-button type="text" size="large" onClick={() => { this.handleChooseBatchStatus({ item, row }) }}>{item.label}</el-button>
                )
              }
            })
          }
        </div>
      )
    },
    /* 点击action按钮事件 */
    handleChooseBatchStatus ({ item, row }) {
      item.func({ type: item.type, row });
    },
    /* 修改事件 */
    handleChooseEdit ({ type, row }) {
      this.$router.push({
        name: 'batchModifyPurchaseEdit',
        query: { type, batchNo: row.batchNo }
      })
    },
    /* 删除事件 */
    handleChooseDelete ({ row }) {
      this.batchDeleteAction(row.batchNo).then(states => {
        if (states) {
          this.$message.success('删除成功');
          this.$refs.tableForm.handleQueryForm();
        }
      })
    },
    /* 查看事件 */
    handleChooseView ({ type, row }) {
      this.$router.push({
        name: 'batchModifyPurchaseView',
        query: { type, batchNo: row.batchNo }
      })
    },
    /* 审核事件 */
    handleChooseAudit ({ row }) {
      this.auditAction({
        url: `/sysback/oa/getAuditPageUrl?oaRequestId=${row.workflowRequestId}`,
        type: 'post'
      });
    },
    /* 审核记录事件 */
    handleChooseAuditRecord ({ row }) {
      this.auditAction({
        url: `/sysback/oa/getAuditPageUrl?oaRequestId=${row.workflowRequestId}`,
        type: 'post'
      });
    },
    /* 新增事件 */
    handleChooseAdd (rawMaterialTodoRecordNo) {
      this.generateBatchNoAction().then(batchNo => {
        this.$router.push({
          name: 'batchModifyPurchaseEdit',
          query: { type: 'add', batchNo, rawMaterialTodoRecordNo: rawMaterialTodoRecordNo || '' }
        })
      })
    },
    /* 删除接口action */
    batchDeleteAction (batchNo) {
      this.tableInfo.loading = true;
      return new Promise(resolve => {
        ApiRequest(
          `/dataBatch/purchasePrice/remove/${batchNo}`,
          'post',
          true
        ).then(res => {
          this.tableInfo.loading = false;
          if (!isResponseSuccess(res)) {
            return false;
          }
          resolve(true);
        }).catch(() => {
          this.tableInfo.loading = false;
        })
      })
    },
    /* 审核和审核记录接口action */
    auditAction (request) {
      let { url, type } = request;
      this.tableInfo.loading = true;
      ApiRequest(
        url,
        type
      ).then(res => {
        this.tableInfo.loading = false;
        if (!isResponseSuccess(res)) {
          return false;
        }
        window.open(res.retData);
      }).catch(() => {
        this.tableInfo.loading = false;
      });
    },
    /* 新增接口action */
    generateBatchNoAction () {
      this.addBtnLoading = true;
      return new Promise(resolve => {
        ApiRequest(
          '/dataBatch/purchasePrice/createBatchNo',
          'get'
        ).then(res => {
          this.addBtnLoading = false;
          if (!isResponseSuccess(res)) {
            return false;
          }
          resolve(res.retData.batchNo)
        }).catch(() => {
          this.addBtnLoading = false;
        })
      })
    },
    /* 改变当前页码事件 */
    handlePageChange (val) {
      this.pagination.nowPage = val;
      this.handleGetTableData();
    },
    /* 改变每页条数事件 */
    handlePageSizeChange (val) {
      this.pagination.pageShow = val;
      this.handleGetTableData();
    },
    /* 获取表单数据 */
    getFormDataFunc (source) {
      /* omit去除多余字段createdAt */
      this.formData = _.omit({
        ...source,
        startCreatedAt: source.createdAt ? source.createdAt[0] : '',
        endCreatedAt: source.createdAt ? source.createdAt[1] : '',
      }, ['createdAt']);
      this.handleGetTableData(1);
    },
    /* 加载表格数据事件 */
    handleGetTableData (pageNum) {
      let curBtnId = getBtnsId('查询');
      sessionStorage.setItem('buttonId', curBtnId);
      if (pageNum) {
        this.pagination.nowPage = pageNum;
      }
      let params = {
        data: this.formData,
        pageNum: this.pagination.nowPage,
        pageSize: this.pagination.pageShow
      };
      this.getTableDataAction(params);
    },
    /* 获取表格数据的Action */
    getTableDataAction (params) {
      this.tableInfo.loading = true;
      ApiRequest(
        '/dataBatch/purchasePrice/page',
        'post',
        params,
        false
      ).then(res => {
        this.tableInfo.loading = false;
        if (!isResponseSuccess(res)) {
          return false;
        }
        this.tableInfo.list = res.retData.records.reduce((value, item) => {
          value.push({
            ...item,
            actions: this.getRowActionsFunc(item.batchStatus) || []
          });
          return value;
        }, []);
        this.pagination.totalNum = res.retData.total;
      }).catch(() => {
        this.tableInfo.loading = false;
      })
    },
    /* 获取对应row的action按钮集合 */
    getRowActionsFunc (batchStatus) {
      const editBtn = {
        label: '修改',
        type: 'edit',
        func: this.handleChooseEdit
      }
      const deleteBtn = {
        label: '删除',
        type: 'delete',
        func: this.handleChooseDelete
      }
      const viewBtn = {
        label: '查看',
        type: 'view',
        func: this.handleChooseView
      }
      const auditBtn = {
        label: '审核',
        type: 'audit',
        func: this.handleChooseAudit
      }
      const auditRecordBtn = {
        label: '审核记录',
        type: 'auditRecord',
        func: this.handleChooseAuditRecord
      }
      // 任务状态： 0:待关联商品 10待导出 20导出中 30待导入 35重新导入 40导入中 50待校验 55 校验中 59 重新校验待提交 60待提交 70 待审核 80 审核成功 90 审核驳回
      const btnList = {
        0: [editBtn, deleteBtn],
        10: [editBtn, deleteBtn],
        20: [editBtn, deleteBtn],
        30: [editBtn, deleteBtn],
        35: [editBtn, deleteBtn],
        40: [editBtn, deleteBtn],
        50: [editBtn, deleteBtn],
        55: [editBtn],
        60: [editBtn, deleteBtn],
        59: [editBtn],
        70: [viewBtn, auditBtn],
        80: [viewBtn, auditRecordBtn],
        90: [editBtn, deleteBtn, auditRecordBtn],
      }
      return btnList[batchStatus];
    }
  }
}
</script>
